package com.sherwin.sourdoughapp.socket

import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableEmitter
import java.lang.Exception

abstract class SocketApi {
    abstract val api : String

    fun send(data : String){
        SocketApiManager.send("$api $data")
    }

    fun sendListener(data: String) : Observable<String>{
        send(data)
        return listener{
            it.onComplete()
        }
    }

    fun onlyListener() : Observable<String>{
        return listener()
    }

    fun listener(onReceive : (ObservableEmitter<String>) -> Unit = {}) : Observable<String>{
        return Observable.create {
            SocketApiManager.addReceiver(object : SocketReceiver{
                override val route: String
                    get() = api

                override fun onReceive(data: String) {
                    SocketApiManager.removeReceiver(this)
                    it.onNext(data)
                    onReceive(it)
                }

                override fun onError(exception: Exception) {
                    SocketApiManager.removeReceiver(this)
                }
            })
        }
    }
}